package com.tzpay.tzpay.presenter;

import android.content.Context;
import android.os.Message;

import com.tzpay.tzpay.R;
import com.tzpay.tzpay.bean.OrderInfo;
import com.tzpay.tzpay.db.OrderDBUtil;
import com.tzpay.tzpay.threadpool.AsyncTaskExecutors;

import java.util.ArrayList;

/**
 * Created by chenfeiyue on 16/3/10.
 */
public class TradeListPresenter implements Presenter {
    public BaseLogicView logicView;
    public Context context;
    public MyHandler handler;
    public boolean isDestory = false;

    public TradeListPresenter(BaseLogicView baseLogicView) {
        this.logicView = baseLogicView;
        context = logicView.getContext();
        handler = new MyHandler(logicView);
    }

    /**
     * select * from table where _id < lastId order by _id desc limit 20;
     *
     * @param selection
     * @param selectionArgs
     * @param sortOrder
     */
    public void getOrderInfos(String selection, String[] selectionArgs, String sortOrder) {
        logicView.showProgress();

        LoadDataRunnable runnable = new LoadDataRunnable(this, selection, selectionArgs, sortOrder);

        AsyncTaskExecutors.executeTask(runnable);
    }

    @Override
    public void onDestory() {
        isDestory = true;
    }

    private static final class LoadDataRunnable implements Runnable {

        private String selection, sortOrder;
        private String[] selectionArgs;

        private TradeListPresenter presenter;

        public LoadDataRunnable(TradeListPresenter presenter, String selection, String[] selectionArgs, String sortOrder) {
            this.presenter = presenter;
            this.selection = selection;
            this.selectionArgs = selectionArgs;
            this.sortOrder = sortOrder;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(500);
                ArrayList<OrderInfo> orderInfos = OrderDBUtil.getInstance(presenter.context)
                        .getOrderInfos(selection, selectionArgs, sortOrder);
                if (presenter.isDestory) {
                    return;
                }
                Message msg = Message.obtain();
                msg.what = MyHandler.MESSAGE_SUCCESS;
                msg.obj = orderInfos;
                presenter.handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
                if (presenter.isDestory) {
                    return;
                }
                Message message = Message.obtain();
                message.what = MyHandler.MESSAGE_FAILED;
                message.obj = presenter.context.getString(R.string.text_no_network);
                presenter.handler.sendMessage(message);
            }
        }
    }
}
